'use client'

import { useState, useEffect } from 'react'
import { SceneGroup } from '@/types/scene'
import { toast } from 'react-hot-toast'
import { PlusIcon } from 'lucide-react'

interface SceneGroupManagerProps {
  groups: SceneGroup[]
  selectedGroupId?: string | 'ungrouped'
  onSelectGroup: (groupId?: string | 'ungrouped') => void
  onGroupsChange: () => void
}

interface DragItem {
  id: string
  type: string
  index: number
}

export default function SceneGroupManager({
  groups,
  selectedGroupId,
  onSelectGroup,
  onGroupsChange
}: SceneGroupManagerProps) {
  const [isAddingGroup, setIsAddingGroup] = useState(false)
  const [newGroupName, setNewGroupName] = useState('')
  const [newGroupDescription, setNewGroupDescription] = useState('')
  const [isDragging, setIsDragging] = useState(false)

  const handleAddGroup = async () => {
    try {
      const res = await fetch('/api/scene-groups', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: newGroupName,
          description: newGroupDescription
        }),
      })

      if (!res.ok) throw new Error('创建分组失败')
      
      setNewGroupName('')
      setNewGroupDescription('')
      setIsAddingGroup(false)
      onGroupsChange()
      toast.success('创建分组成功')
    } catch (error) {
      console.error('创建分组失败:', error)
      toast.error('创建分组失败')
    }
  }

  const handleDeleteGroup = async (groupId: string) => {
    if (!confirm('确定要删除此分组吗？分组内的场景将被移至未分组。')) {
      return
    }

    try {
      const res = await fetch(`/api/scene-groups/${groupId}`, {
        method: 'DELETE',
      })

      if (!res.ok) throw new Error('删除分组失败')
      
      if (selectedGroupId === groupId) {
        onSelectGroup(undefined)
      }
      onGroupsChange()
      toast.success('删除分组成功')
    } catch (error) {
      console.error('删除分组失败:', error)
      toast.error('删除分组失败')
    }
  }

  const handleDragStart = (e: React.DragEvent, groupId: string, index: number) => {
    e.dataTransfer.setData('text/plain', JSON.stringify({ id: groupId, index }))
    setIsDragging(true)
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
  }

  const handleDrop = async (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault()
    setIsDragging(false)

    const data = JSON.parse(e.dataTransfer.getData('text/plain'))
    const sourceIndex = data.index

    if (sourceIndex === targetIndex) return

    try {
      const res = await fetch('/api/scene-groups/reorder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          groupId: data.id,
          sourceIndex,
          targetIndex
        }),
      })

      if (!res.ok) throw new Error('重新排序失败')
      onGroupsChange()
    } catch (error) {
      console.error('重新排序失败:', error)
      toast.error('重新排序失败')
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h2 className="text-lg font-medium text-white/90">场景分组</h2>
      </div>

      <div className="space-y-2">
        <button
          onClick={() => onSelectGroup(undefined)}
          className={`w-full text-left px-4 py-3 rounded-lg transition-all duration-200 
            ${!selectedGroupId 
              ? 'bg-gradient-to-r from-primary-500/20 to-primary-500/10 border-l-4 border-l-primary-500 shadow-lg' 
              : 'hover:bg-white/5'
            }`}
        >
          <div className="flex items-center space-x-2">
            <span className={!selectedGroupId ? 'text-primary-300 font-medium' : 'text-white/70'}>
              全部场景
            </span>
            {!selectedGroupId && (
              <div className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-pulse" />
            )}
          </div>
        </button>

        <button
          onClick={() => onSelectGroup('ungrouped')}
          className={`w-full text-left px-4 py-3 rounded-lg transition-all duration-200
            ${selectedGroupId === 'ungrouped'
              ? 'bg-gradient-to-r from-primary-500/20 to-primary-500/10 border-l-4 border-l-primary-500 shadow-lg' 
              : 'hover:bg-white/5'
            }`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <span className={selectedGroupId === 'ungrouped' ? 'text-primary-300 font-medium' : 'text-white/70'}>
                未分组
              </span>
              <span className="text-xs text-white/50">(默认)</span>
            </div>
            {selectedGroupId === 'ungrouped' && (
              <div className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-pulse" />
            )}
          </div>
        </button>

        <div className={`mt-4 pt-4 border-t border-white/10 space-y-2 ${isDragging ? 'opacity-50' : ''}`}>
          {groups.map((group, index) => (
            <div
              key={group.id}
              draggable
              onDragStart={(e) => handleDragStart(e, group.id, index)}
              onDragOver={handleDragOver}
              onDrop={(e) => handleDrop(e, index)}
              className={`group relative flex items-center px-4 py-3 rounded-lg cursor-move transition-all duration-200 
                ${selectedGroupId === group.id
                  ? 'bg-gradient-to-r from-primary-500/20 to-primary-500/10 border-l-4 border-l-primary-500 shadow-lg' 
                  : 'hover:bg-white/5'
                }`}
            >
              <button
                onClick={() => onSelectGroup(group.id)}
                className="flex-1 min-w-0"
              >
                <div className="flex items-center space-x-2">
                  <span 
                    className={`truncate font-medium ${
                      selectedGroupId === group.id 
                        ? 'text-primary-300' 
                        : 'text-white/70'
                    }`}
                  >
                    {group.name}
                  </span>
                  {selectedGroupId === group.id && (
                    <div className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-pulse flex-shrink-0" />
                  )}
                </div>
              </button>
              <div className="flex items-center ml-3 flex-shrink-0">
                <button
                  onClick={() => handleDeleteGroup(group.id)}
                  className="px-2 py-1 text-xs text-red-400 hover:text-red-300 transition-colors opacity-0 group-hover:opacity-100 whitespace-nowrap"
                >
                  删除
                </button>
              </div>
              
              {/* 悬浮提示框 */}
              {group.description && (
                <div className="absolute left-0 right-0 -top-12 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none">
                  <div className="mx-4 p-2 text-xs text-white/90 bg-gray-900/95 rounded-lg shadow-lg border border-white/10 backdrop-blur-sm">
                    {group.description}
                  </div>
                  <div className="absolute -bottom-1 left-7 w-2 h-2 bg-gray-900/95 border-r border-b border-white/10 transform rotate-45" />
                </div>
              )}
            </div>
          ))}

          <button
            onClick={() => setIsAddingGroup(true)}
            className="w-full flex items-center justify-center px-4 py-2.5 
                     text-white/50 hover:text-white/70 hover:bg-white/5 
                     rounded-lg border border-dashed border-white/10 
                     transition-colors"
          >
            <PlusIcon className="w-4 h-4 mr-2" />
            添加分组
          </button>
        </div>
      </div>

      {isAddingGroup && (
        <div className="mt-4 p-4 bg-background-paper/30 backdrop-blur-lg border border-white/10 rounded-lg">
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-white/80 mb-1">
                分组名称
              </label>
              <input
                type="text"
                value={newGroupName}
                onChange={(e) => setNewGroupName(e.target.value)}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg
                         text-white/90 placeholder-white/30
                         focus:outline-none focus:ring-2 focus:ring-primary-500/50"
                placeholder="输入分组名称"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-white/80 mb-1">
                描述
              </label>
              <input
                type="text"
                value={newGroupDescription}
                onChange={(e) => setNewGroupDescription(e.target.value)}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg
                         text-white/90 placeholder-white/30
                         focus:outline-none focus:ring-2 focus:ring-primary-500/50"
                placeholder="输入分组描述（可选）"
              />
            </div>
            <div className="flex justify-end space-x-2">
              <button
                onClick={() => setIsAddingGroup(false)}
                className="px-3 py-1.5 text-sm bg-white/5 text-white/70 rounded-lg
                         hover:bg-white/10 hover:text-white/90 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleAddGroup}
                disabled={!newGroupName}
                className="px-3 py-1.5 text-sm bg-primary-500 text-white rounded-lg
                         hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed
                         transition-colors"
              >
                添加
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
} 